/*
 * VHKOMatchGrid.java
 * Created on 8 août 2009
 *
 * VirtualHockey Internet Platform
 * http://code.google.com/p/virtualhockey/
 *
 * Copyright (c) 2005-2009, Jens and Jan Janke (VirtualHockey Project)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
 */

package com.hockeo.vhweb.client.ui.widget;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.store.GroupingStore;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.grid.GridGroupRenderer;
import com.extjs.gxt.ui.client.widget.grid.GroupColumnData;
import com.extjs.gxt.ui.client.widget.grid.GroupingView;
import com.extjs.gxt.ui.client.widget.grid.RowNumberer;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.hockeo.vhweb.client.VHMain;
import com.hockeo.vhweb.client.mvc.VHController;
import com.hockeo.vhweb.client.res.VHResConstants;
import com.hockeo.vhweb.client.rpc.VHRpcResultReceiver;
import com.hockeo.vhweb.client.ui.menu.VHGridContextMenu;
import com.hockeo.vhweb.client.ui.menu.VHMatchInfoContextMenu;
import com.hockeo.vhweb.client.utils.VHJsData;

/**
 * Represents a list of KO matches grouped by contest round.
 *
 * @version $Id$
 * @author jjanke
 */
public class VHKOMatchGrid extends LayoutContainer implements VHRpcResultReceiver<List<VHJsData>>
{
  private static final int              HEIGHT_ROUND_HEADER = 29;
  private static final int              HEIGHT_MATCH        = 24;
  private static final String           MATCH_RESULT_PREFIX = "match_result_";

  private final VHGridContextMenu       d_ctxmenu;
  private final GroupingStore<VHJsData> d_store;
  private Grid<VHJsData>                d_grid;
  private final int                     d_nMaxMatches;
  private final boolean                 d_fShowLeagueCategory;

  /**
   * Builds a new KO match grid.
   *
   * @param nMaxMatches the maximum number of matches in one KO series
   * @param fShowLeagueCategory indicates whether the league category should be shown
   *          behind a club's name in brackets
   */
  public VHKOMatchGrid( VHController controller, int nMaxMatches, boolean fShowLeagueCategory )
  {
    d_store = new GroupingStore<VHJsData>();
    d_nMaxMatches = nMaxMatches;
    d_fShowLeagueCategory = fShowLeagueCategory;

    buildGrid();
    setLayout( new FitLayout() );
    add( d_grid );

    d_ctxmenu = new VHMatchInfoContextMenu( controller, d_grid, "clubHome_", "clubAway_" );
  }

  public void setRpcData( List<VHJsData> listKOMatches, String strPurpose )
  {
    d_store.removeAll();
    d_store.add( listKOMatches );
    d_store.groupBy( "round_num" );
  }

  private void buildGrid()
  {
    final VHResConstants constants = VHMain.getConstants();

    // Cell rendering
    //
    GridCellRenderer<VHJsData> renderer = new GridCellRenderer<VHJsData>() {
      @SuppressWarnings( "synthetic-access" )
      public String render( VHJsData kom, String strProperty, ColumnData config, int rowIndex, int colIndex,
          ListStore<VHJsData> store, Grid<VHJsData> grid )
      {
        if ( strProperty.equals( "clubHome_country" ) )
          return "<img src='images/flags/16x16/" + kom.getString( "clubHome_country" ) + ".png'/>";
        else if ( strProperty.equals( "clubAway_country" ) )
          return "<img src='images/flags/16x16/" + kom.getString( "clubAway_country" ) + ".png'/>";
        else if ( strProperty.equals( "clubHome_name" ) )
        {
          String strClubName = kom.getString( "clubHome_name" );

          if ( d_fShowLeagueCategory )
            strClubName += " (" + kom.getInt( "clubHome_league_category" ) + ")";

          if ( kom.getBoolean( "clubHomeWinner" ) )
            strClubName = "<span style='font-weight: bold;'>" + strClubName + "</span>";

          return strClubName;
        }
        else if ( strProperty.equals( "clubAway_name" ) )
        {
          String strClubName = kom.getString( "clubAway_name" );

          if ( d_fShowLeagueCategory )
            strClubName += " (" + kom.getInt( "clubAway_league_category" ) + ")";

          if ( kom.getBoolean( "clubAwayWinner" ) )
            strClubName = "<span style='font-weight: bold;'>" + strClubName + "</span>";

          return strClubName;
        }
        else if ( strProperty.equals( "numWinsTotalHome" ) )
        {
          return "(" + kom.getInt( "numWinsTotalHome" ) + constants.matchGoalsSeparator()
              + kom.getInt( "numWinsTotalAway" ) + ")";
        }
        else if ( strProperty.startsWith( MATCH_RESULT_PREFIX ) )
        {
          int iMatch = Integer.parseInt( strProperty.substring( MATCH_RESULT_PREFIX.length() ) );
          VHJsData m = (VHJsData) kom.getChild( iMatch );

          if ( m == null || m.getBoolean( "notRequired" ) )
            return "";

          if ( !kom.getBoolean( "played" ) )
            return constants.matchGoalsNotPlayed();

          String strResult = m.getInt( "goalsHome" ) + constants.matchGoalsSeparator() + m.getInt( "goalsAway" );

          if ( m.getBoolean( "decidedByShootout" ) )
            strResult += " <span title='" + constants.afterShootoutToolTip() + "'>" + constants.afterShootout()
                + "</span>";

          return strResult;
        }

        return String.valueOf( kom.get( strProperty ) );
      }
    };

    // Column definitions
    //
    ArrayList<ColumnConfig> listCols = new ArrayList<ColumnConfig>();
    ColumnConfig col;

    RowNumberer rowNumberer = new RowNumberer();
    listCols.add( rowNumberer );

    col = new ColumnConfig();
    col.setId( "round_num" );
    col.setWidth( 26 );
    col.setAlignment( HorizontalAlignment.RIGHT );
    col.setResizable( false );
    col.setHidden( true );
    col.setMenuDisabled( true );
    col.setSortable( false );
    listCols.add( col );

    col = new ColumnConfig();
    col.setId( "clubHome_country" );
    col.setWidth( 26 );
    col.setRenderer( renderer );
    col.setAlignment( HorizontalAlignment.CENTER );
    col.setResizable( false );
    col.setGroupable( false );
    col.setMenuDisabled( true );
    col.setSortable( false );
    listCols.add( col );

    col = new ColumnConfig();
    col.setId( "clubHome_name" );
    col.setWidth( 200 );
    col.setRenderer( renderer );
    col.setGroupable( false );
    col.setMenuDisabled( true );
    col.setSortable( false );
    listCols.add( col );

    col = new ColumnConfig();
    col.setId( "clubAway_country" );
    col.setWidth( 26 );
    col.setRenderer( renderer );
    col.setAlignment( HorizontalAlignment.CENTER );
    col.setResizable( false );
    col.setGroupable( false );
    col.setMenuDisabled( true );
    col.setSortable( false );
    listCols.add( col );

    col = new ColumnConfig();
    col.setId( "clubAway_name" );
    col.setWidth( 200 );
    col.setRenderer( renderer );
    col.setGroupable( false );
    col.setMenuDisabled( true );
    col.setSortable( false );
    listCols.add( col );

    col = new ColumnConfig();
    col.setId( "numWinsTotalHome" );
    col.setWidth( 50 );
    col.setRenderer( renderer );
    col.setGroupable( false );
    col.setMenuDisabled( true );
    col.setSortable( false );
    listCols.add( col );

    // Add a column for each contained match
    //
    for ( int i = 0; i < d_nMaxMatches; i++ )
    {
      col = new ColumnConfig();
      col.setId( MATCH_RESULT_PREFIX + i );
      col.setWidth( 50 );
      col.setRenderer( renderer );
      col.setGroupable( false );
      col.setMenuDisabled( true );
      col.setSortable( false );
      listCols.add( col );
    }

    final ColumnModel cm = new ColumnModel( listCols );

    // Header cells with tooltips
    //
    GroupingView view = new GroupingView();

    view.setForceFit( true );
    view.setGroupRenderer( new GridGroupRenderer() {
      public String render( GroupColumnData data )
      {
        VHJsData matchFirst = (VHJsData) data.models.get( 0 );
        if ( matchFirst.getDate( "moveday_date" ) != null )
          return VHMain.getMessages().roundHeaderWithDate( matchFirst.getString( "round_type_translated" ),
              matchFirst.getInt( "moveday_id" ), matchFirst.getDate( "moveday_date" ) );

        return VHMain.getMessages().roundHeader( matchFirst.getString( "round_type_translated" ),
            matchFirst.getInt( "moveday_id" ) );
      }
    } );

    // Grid
    //
    d_grid = new Grid<VHJsData>( d_store, cm );
    d_grid.addPlugin( rowNumberer );
    d_grid.setView( view );
    d_grid.setHideHeaders( true );
    d_grid.setStripeRows( true );
    d_grid.setBorders( true );
    d_grid.setAutoWidth( true );
  }
}
